#!/usr/bin/env python
# -*- coding: utf8 -*-
"""
Testing BlogoSerV unopurpose client
"""

import sys
import socket
import mimetypes

HOST = '127.0.0.1'
PORT = 5007

MAX_PACKET = 1024

UTILNAME = 'client'

if len(sys.argv) < 2 or sys.argv[1] in ( '-h', '--help' ):
  sys.stderr.write( 'Usage: %s <filetosend>\n' % ( UTILNAME ) )
  sys.exit( 1 )

try:
  fd = open( sys.argv[1], 'r' )
except:
  sys.stderr.write( 'Cannot open file\n' )
  sys.exit( 1 )


data = fd.read()
ContentLength = len( data )
ContentType   = mimetypes.guess_type( fd.name )[0]

if ContentType is None:
  ContentType = 'unknown'  

sock = socket.socket( 2, 1 )
sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
try:
  sock.connect( ( HOST, PORT ) )
except:
  fd.close()
  sys.stderr.write( '{E} Fault to connect\n' )
  sys.exit( 1 )

# data transfer here
intbytes = sock.send( 'POST / HTTP/1.0\nContent-Length: %d\nContent-Type: %s\n\n' % ( ContentLength, ContentType ) )
sys.stdout.write( 'POST sended in %d bytes\n' % ( intbytes ) )
intbytes = sock.send( data )
sys.stdout.write( 'XML sended in %d bytes\n' % ( intbytes ) )


# get reply
sys.stdout.write( '[*] Responce:\n' )
fd = sock.makefile()
try:
  sys.stdout.write( fd.read( ) )
except:
  sys.stderr.write( '{E} Catch signal' )

sys.stdout.flush()
  

# get out from here
sock.shutdown( 2 )
sock.close()
sys.exit( 0 )
